<template>
  <SkeletonCpt v-if="!detail" />
  <div
    v-else
    class="article-detail-wrap"
  >
    <h1 class="title">
      {{ detail.title }}
    </h1>

    <div class="summary-wrap">
      <div class="summary">
        <img
          v-if="detail.users && detail.users[0]"
          class="user-avatar"
          :src="detail.users[0].avatar"
          alt=""
        >
        <span
          v-if="detail.types && detail.types[0]"
          class="type"
        >
          <el-icon><FolderOpened /></el-icon>
          {{ detail.types[0].name }}
        </span>
        <span>
          <el-icon>
            <ChatLineRound />
          </el-icon>
          {{ detail.comment_total || 0 }}
        </span>
        <span>
          <el-icon><View /></el-icon>
          {{ detail.click || 0 }}
        </span>
        <span>
          <el-icon><Star /></el-icon>
          {{ detail.star_total || 0 }}
        </span>
      </div>
      <div class="date">
        <span>发表于: {{ $filters.formatDate(detail.created_at) }}</span>
      </div>
    </div>

    <img
      v-if="detail['head_img']"
      v-lazy="detail['head_img']"
      class="head-img"
    >
    <div v-else />

    <p class="desc">
      简介: {{ detail.desc || '暂无~' }}
    </p>

    <RenderMarkdownCpt
      ref="hssMd"
      class="hss-mdd"
      :md="detail.content"
    />

    <div class="tag-list">
      <el-icon><CollectionTag /></el-icon>
      <div v-if="detail.tags && detail.tags.length">
        <el-tag
          v-for="item in detail.tags"
          :key="item.id"
          class="hss-el-tag"
          :color="item.color"
          size="small"
        >
          {{ item.name }}
        </el-tag>
      </div>
      <span v-else>该文章没有关联标签~</span>
    </div>

    <div class="star-wrap">
      如果本文章对你有所帮助，欢迎点赞~
      <div class="icon">
        <span
          v-if="detail.is_star"
          v-loading="starLoaing"
        >
          <el-tooltip
            class="item"
            effect="dark"
            content="取消点赞"
            placement="top"
          >
            <el-icon @click="starForArticle(0, detail)"><StarFilled /></el-icon>
          </el-tooltip>
        </span>
        <span v-else>
          <el-tooltip
            class="item"
            effect="dark"
            content="赞一个"
            placement="top"
          >
            <el-icon @click="starForArticle(1, detail)"><Star /></el-icon>
          </el-tooltip>
        </span>
        {{ detail.star_info && detail.star_info.count }}
      </div>
    </div>
    <p class="last-update">
      最后更新于：{{ $filters.formatDate(detail.updated_at) }}
    </p>

    <div class="comment-wrap">
      <div v-if="detail.is_comment === 1">
        <el-divider>欢迎评论留言~</el-divider>
        <div>
          <AsyncTextareaInputCpt @content-change="contentChange" />
          <div class="btn">
            <el-button
              type="primary"
              :loading="submitCommentLoading"
              @click="addComment"
            >
              发表评论
            </el-button>
          </div>

          <!-- 评论组件 -->
          <AsyncCommentCpt
            v-loading="isLoading"
            :list="commentList"
            :total="total"
            :sort="sort"
            :has-more="hasMore"
            :now-page="nowPage"
            :page-size="pageSize"
            :children-page-size="comment.childrenPageSize"
            @refresh="refreshCommentList"
            @delete-reply="deleteReply"
            @sort-change="sortChange"
            @handle-parent-page="handleParentPage"
            @handle-children-page="handleChildrenPage"
          />
        </div>
      </div>
      <el-divider v-else>
        该文章暂未开启评论~
      </el-divider>
    </div>
  </div>
</template>

<script lang="ts" setup>
import RenderMarkdownCpt from '@/components/RenderMarkdown/index.vue'
import AsyncTextareaInputCpt from '@/components/TextareaInput/index.vue'
import AsyncCommentCpt from '@/components/Comment/index.vue'
import SkeletonCpt from '@/components/Skeleton.vue'

import { useRoute } from 'vue-router'

import { inject, ref, onBeforeMount, onMounted, onUnmounted, watch, getCurrentInstance, nextTick } from 'vue'

import { userStore } from '@/store/user'
import { appStore } from '@/store/app'
import { articleStore } from '@/store/article'
import { commentStore } from '@/store/comment'

const $get:any = inject('$get')
const $post:any = inject('$post')
const $newmessage:any = inject('$newmessage')

const route = useRoute()
// 获取当前组件实例
const { ctx } = getCurrentInstance()

const user = userStore()
const app = appStore()
const article = articleStore()
const comment = commentStore()

const sort = ref('')
const commentList:any = ref([])
const total = ref(0)
const hasMore = ref(false)

const detail:any = ref({})
const articleId:any = ref('')
const starLoaing = ref(false)

const submitCommentLoading = ref(false)
const isLoading = ref(false)
const commentContent = ref('')
const nowPage = ref(undefined)
const pageSize = ref(0)

const hssMd:any = ref<HTMLElement | null>(null)

watch(() => user.userInfo, (newVal, oldVal) => {
  refreshCommentList()
})

onBeforeMount(async () => {
  app.setShowCatalog(true)

  articleId.value = route.params.id
  detail.value = await $get(`article/find/${articleId.value}`)
  document.title = `${detail.value && detail.value.title} - 小锅锅·博客`
  let commentData:any = {}
  let commentParams = {}
  const orderName = 'created_at'
  if (detail.value.is_comment === 1) {
    commentParams = {
      article_id: articleId,
      nowPage: 1, // 当前父评论页数
      pageSize: 2, // 当前父评论分页大小
      childrenPageSize: comment.childrenPageSize, // 当前子评论分页大小
      orderName,
      orderBy: 'desc'
    }
    commentData = await $get('comment/comment', commentParams)
  }
  sort.value = orderName === 'created_at' ? 'date' : 'hot'
  commentList.value = commentData.rows
  total.value = commentData.total
  hasMore.value = commentData.hasMore
})

// 页面加载时
onMounted(async () => {
  console.log('%c页面加载耗时：13ms | Theme By Joe', 'color:#fff; background: linear-gradient(270deg, #986fee, #8695e6, #68b7dd, #18d7d3); padding: 8px 15px; border-radius: 0 15px 0 15px')
  window.scrollTo({ top: 0 })
  console.log('DOM挂载完毕')
  nextTick(() => {
    setTimeout(() => {
      renderCatalog()
    }, 1000)
  })
})

onUnmounted(() => {
  app.setShowCatalog(false)
  article.changeCatalogList([])
})

const getArticleDetail = async () => {
  try {
    detail.value = await $get(
      'article/find', {
        id: articleId.value
      }
    )
  } catch (error) {
    console.log(error)
  }
}

const sortChange = async (_sort:any) => {
  sort.value = _sort
  refreshCommentList()
}

const deleteReply = async (item:any) => {
  if (item.parent_comment_id !== -1) {
    for (let index = 0; index < commentList.value.length; index++) {
      const element:any = commentList.value[index]
      if (element.id === item.parent_comment_id) {
        for (
          let index = 0;
          index < element.children_comment.length;
          index++
        ) {
          const child = element.children_comment[index]
          if (child.id === item.id) {
            element.children_comment.splice(index, 1)
            break
          }
        }
      }
    }
  }
}

// 留言列表
const refreshCommentList = async () => {
  const query = {
    article_id: articleId.value,
    nowPage: nowPage.value,
    pageSize: pageSize.value,
    childrenPageSize: comment.childrenPageSize,
    orderName: sort.value === 'date' ? 'created_at' : 'star_total',
    orderBy: 'desc'
  }
  try {
    isLoading.value = true
    const commentData = await $get('comment/comment', { ...query })
    isLoading.value = false
    commentList.value = commentData.rows
    total.value = commentData.total
    hasMore.value = commentData.hasMore
  } catch (error) {
    console.log(error)
    isLoading.value = false
  }
}

// 获取子评论分页
const handleChildrenPage = async (query:any) => {
  try {
    const { data } = await $get('comment/comment_children', {
      parent_comment_id: query.parent_comment_id,
      article_id: query.article_id,
      pageSize: query.childrenPageSize,
      childrenPageSize: comment.childrenPageSize
    })
    commentList.value.forEach((item:any) => {
      if (item.id === query.parent_comment_id) {
        item.children_comment.push(...data.rows)
      }
    })
  } catch (error) {
    console.log(error)
  }
}
// 获取父评论分页
const handleParentPage = async (query:any) => {
  try {
    const commentData = await $get('comment/comment', {
      article_id: articleId.value,
      nowPage: query.nowPage + 1,
      pageSize: pageSize.value,
      childrenPageSize: comment.childrenPageSize,
      orderName: query.orderName,
      orderBy: query.orderBy
    })
    commentList.value.push(...commentData.rows)
    hasMore.value = commentData.hasMore
  } catch (error) {
    console.log(error)
  }
}

// 新增回复
const addComment = async () => {
  if (!user.userInfo) {
    $newmessage('暂未登录，请登录！', 'warning')
    return
  }
  if (commentContent.value.length < 5) {
    $newmessage('评论内容至少5个字符~', 'warning')
    return
  }
  try {
    submitCommentLoading.value = true
    await $post('comment/create', {
      article_id: detail.value.id,
      content: commentContent.value,
      parent_comment_id: -1,
      reply_comment_id: -1,
      to_user_id: -1
    })
    submitCommentLoading.value = false
    $newmessage('评论成功~', 'success')
    refreshCommentList()
  } catch (error) {
    console.log(error)
    submitCommentLoading.value = false
  }
}
const contentChange = (newVal:any) => {
  commentContent.value = newVal
}

// 给文章点赞/取消点赞
const starForArticle = async (type:number, articleDetail:any) => {
  try {
    if (user.userInfo) {
      starLoaing.value = true
      if (type === 1) {
        await $post('star/create', {
          article_id: articleDetail.id,
          from_user_id: user.userInfo.id,
          comment_id: -1,
          to_user_id: -1
        })
        $newmessage('点赞成功！', 'success')
        await getArticleDetail()
        starLoaing.value = false
      } else {
        await $post(
              `star/delete/${articleDetail.is_star_id}`
        )
        await getArticleDetail()
        $newmessage('取消点赞成功!', 'success')
        starLoaing.value = false
      }
    } else {
      $newmessage('暂未登录，请登录！', 'warning')
    }
  } catch (error) {
    console.log(error)
  }
}

// 渲染文章目录
const renderCatalog = () => {
  const list = ['H1', 'H2', 'H3', 'H4', 'H5', 'H6']
  hssMd.value ||= ctx.$refs.hssMd
  const md = hssMd.value.$el.childNodes[0].childNodes[0].children || []

  const arr = []

  for (let i = 0; i < md.length; i++) {
    const item = md[i]

    if (item.nodeType === 1 && list.includes(item.nodeName)) {
      const obj:any = {}
      obj.id =
              item.innerText.slice(0, 10) +
              '_' +
              Math.floor(Math.random() * 100 + 1)
      obj.type = item.nodeName
      obj.text = item.innerText
      // 创建一个a元素
      const ele1 = document.createElement('a')
      ele1.setAttribute('id', obj.id)
      item.appendChild(ele1)
      arr.push(obj)
    }
  }
  article.changeCatalogList(arr)
}

</script>

<style lang="scss" scoped>
@import '@/assets/css/constant.scss';

.article-detail-wrap {
  .title {
    text-align: center;
  }
  .summary-wrap {
    .summary,
    .date {
      display: flex;
      align-items: center;
      justify-content: space-around;
      margin: 0 auto;
      margin-bottom: 10px;
      width: 200px;
      font-size: 12px;
    }
    .summary {
      .user-avatar {
        width: 25px;
        height: 25px;
        border-radius: 50%;
      }
    }
  }

  .tag-list {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    margin: 10px 0;
    .el-icon {
      font-size: 18px;
    }
    .hss-el-tag {
      margin: 4px;
      border: none;
      color: $theme-color6;
    }
  }
  .star-wrap {
    display: flex;
    align-items: center;
    min-height: 40px;
    .icon {
      margin-left: 5px;
      cursor: pointer;
    }
    .avatar-list {
      margin-left: 10px;
    }
  }
  .last-update {
    text-align: right;
  }
  .comment-wrap {
    .btn {
      margin-top: 20px;
      text-align: right;
    }
  }
}
</style>

<style lang="scss" scoped>
@import '@/assets/css/constant.scss';
@media screen and (max-width: 540px) {
  .main {
    margin: 135px auto 0;
    padding: 0;
  }
  .content {
    padding: 0 10px;
  }
}
.avatar {
  margin-right: 5px;
  width: 20px;
  height: 20px;
  border-radius: 50%;
}
.desc-wrap {
  padding-bottom: 10px;
}
.star {
  cursor: pointer;
}
.little-tag {
  display: inline-block;
  margin-right: 5px;
  padding: 0 5px;
  border-radius: 3px;
  background-color: #aaaaaa;
  color: $theme-color6;
  text-align: center;
}
.head-img {
  width: 100%;
}
</style>
